package com.example.integration.impl;

import com.example.integration.UserInfoProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 第三方服务提供者实现类
 * 负责调用其他部门的 HTTP 接口获取用户信息
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Slf4j
@Component
public class UserInfoProviderImpl implements UserInfoProvider {
    
    @Value("${integration.user-service.url:http://localhost:8081/api/user}")
    private String userServiceUrl;
    
    private final RestTemplate restTemplate;
    
    public UserInfoProviderImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    @Override
    public String getUserInfo(String userId) {
        try {
            log.info("调用第三方用户服务获取用户信息，userId={}, url={}", userId, userServiceUrl);
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 构建请求参数
            Map<String, String> params = new HashMap<>();
            params.put("userId", userId);
            
            HttpEntity<Map<String, String>> request = new HttpEntity<>(params, headers);
            
            // 调用第三方 HTTP 接口
            ResponseEntity<String> response = restTemplate.exchange(
                    userServiceUrl + "/info",
                    HttpMethod.POST,
                    request,
                    String.class
            );
            
            log.info("第三方用户服务调用成功，userId={}, response={}", userId, response.getBody());
            return response.getBody();
            
        } catch (Exception e) {
            log.error("调用第三方用户服务异常，userId={}, url={}", userId, userServiceUrl, e);
            throw new RuntimeException("获取用户信息失败", e);
        }
    }
}

